﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using Application = System.Windows.Forms.Application;

namespace Связь_с_БД
{
    class PrintDocumentOrderOnTransfer
    {
        public PrintDocumentOrderOnTransfer(DataGridViewRow dgvr, string[] str)
        {
            _orderOnTransferReplace = new string[21];
            _dataGridViewRow = dgvr;
            _strings = str;
        }

        public bool IsClosed;

        private readonly string filePath = @"\PatternDocuments\orderOnTransfer.docx";

        private readonly string[] _orderOnTransfer = {
                                                           "{FIO}",
                                                           "{numberCourse}",
                                                           "{group}",
                                                           "{formEducation}",
                                                           "{codeDirection}",
                                                           "{nameDirection}",
                                                           "{codeProphyle}",
                                                           "{nameProphyle}",
                                                           "{numbercourse2}",
                                                           "{formEducation2}",
                                                           "{codeDirection2}",
                                                           "{nameDirection2}",
                                                           "{codeProphyle2}",
                                                           "{nameProphyle2}",
                                                           "{date}",
                                                           "{group2}",
                                                           "{numberDeal}",
                                                           "{dateDeal}",
                                                           "{numberDeal2}",
                                                           "{dateDeal2}",
                                                           "{ground}"
                                                       };
        private string[] _orderOnTransferReplace;
        private string[] _strings;
        private DataGridViewRow _dataGridViewRow;

        private void SetOrderOnTransferValues()
        {
            _orderOnTransferReplace[0] = _dataGridViewRow.Cells[27].Value.ToString();
            _orderOnTransferReplace[1] = GetNumberCourse(_dataGridViewRow.Cells[22].Value.ToString());
            _orderOnTransferReplace[2] = _dataGridViewRow.Cells[22].Value.ToString();
            _orderOnTransferReplace[3] = _strings[0];
            _orderOnTransferReplace[4] = _dataGridViewRow.Cells[13].Value.ToString();
            _orderOnTransferReplace[5] = _dataGridViewRow.Cells[14].Value.ToString();
            _orderOnTransferReplace[6] = _dataGridViewRow.Cells[16].Value.ToString();
            _orderOnTransferReplace[7] = _dataGridViewRow.Cells[15].Value.ToString();
            _orderOnTransferReplace[8] = GetNumberCourse(_dataGridViewRow.Cells[22].Value.ToString());
            _orderOnTransferReplace[9] = _strings[1];
            _orderOnTransferReplace[10] = _strings[2];
            _orderOnTransferReplace[11] = _strings[3];
            _orderOnTransferReplace[12] = _strings[4];
            _orderOnTransferReplace[13]= _strings[5];
            _orderOnTransferReplace[14]= _strings[6];
            _orderOnTransferReplace[15]= _strings[7];
            _orderOnTransferReplace[16]= _strings[8];
            _orderOnTransferReplace[17]= _strings[9];
            _orderOnTransferReplace[18]= _strings[10];
            _orderOnTransferReplace[19]= _strings[11];
            _orderOnTransferReplace[20]= _strings[12];
        }

        private void ReplaceText(string text, string replaceText, Document worddocument, Word.Application wordapp)
        {
            Object start = 0;
            Object end = worddocument.Characters.Count;
            Range wordrange = worddocument.Range(ref start, ref end);
            wordrange.TextRetrievalMode.IncludeHiddenText = false;
            wordrange.TextRetrievalMode.IncludeFieldCodes = false;
            //MessageBox.Show(wordrange.Text);

            int beginphrase = 0;
            beginphrase = wordrange.Text.IndexOf(text);
            start = beginphrase;
            end = beginphrase + text.Length;
            wordrange = worddocument.Range(ref start, ref end);
            //MessageBox.Show(wordrange.Text + " Найденный текст начинается с позиции: "
            // + Convert.ToString(beginphrase));
            //ставим курсор в начало документа
            object unit = WdUnits.wdStory;
            object extend = WdMovementType.wdMove;
            wordapp.Selection.HomeKey(ref unit, ref extend);

            //переходим к началу нужной фразы
            unit = WdUnits.wdCharacter;
            extend = WdMovementType.wdMove;
            object count = beginphrase;
            wordapp.Selection.MoveRight(ref unit, ref count, ref extend);

            //выделяем это слово
            unit = WdUnits.wdCharacter;
            count = text.Length;
            extend = WdMovementType.wdExtend;
            wordapp.Selection.MoveRight(ref unit, ref count, ref extend);

            wordapp.Options.Overtype = false;
            wordapp.Selection.Font.Name = @"Times New Roman";
            wordapp.Selection.Font.Size = 14;
            wordapp.Selection.Font.Color = WdColor.wdColorBlack;
            wordapp.Selection.TypeText(replaceText);
        }

        private string GetNumberCourse(string str)
        {
            string result;
            int index = str.IndexOf("-");
            index++;
            result = str.Substring(index, 1);
            return result;
        }

        public void InsertInDocument()
        {
            var wordapp = new Word.Application();
            wordapp.DocumentBeforeClose += WordappDocumentBeforeClose;
            string FilePath = Application.StartupPath + filePath;
            try
            {
                var worddoc = wordapp.Documents.Open(FilePath);
                SetOrderOnTransferValues();
                for (int i = 0; i < _orderOnTransferReplace.Length; i++)
                    ReplaceText(_orderOnTransfer[i], _orderOnTransferReplace[i], worddoc, wordapp);

                object nameFormat =
                    WdSaveFormat.wdFormatDocumentDefault;
                worddoc.SaveAs(Application.StartupPath + "\\okok", nameFormat);
                wordapp.Visible = true;
                IsClosed = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                wordapp.Quit();
            }
        }

        void WordappDocumentBeforeClose(Document doc, ref bool cancel)
        {
            IsClosed = true;
        }
    }
}
